package com.pub.paypal.common.operation;

import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import com.paypal.payments.CapturesGetRequest;
import com.pub.paypal.common.util.PayPalClient;
import com.pub.paypal.common.vo.PaypalVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.json.JSONObject;

import com.paypal.http.serializer.Json;
import com.paypal.payments.LinkDescription;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class CaptureOrder extends PayPalClient {
    /**
     * 用户授权支付成功，进行扣款操作
     */
    public PaypalVo captureOrder(String orderId) throws IOException {
        PaypalVo paypalVo = new PaypalVo();
        OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
        request.requestBody(new OrderRequest());
        PayPalClient payPalClient = new PayPalClient();
        HttpResponse<Order> response = null;
        try {
            response = payPalClient.client().execute(request);
        } catch (IOException e1) {
            try {
                log.error("第1次调用paypal扣款失败");
                response = payPalClient.client().execute(request);
            } catch (Exception e) {
                try {
                    log.error("第2次调用paypal扣款失败");
                    response = payPalClient.client().execute(request);
                } catch (Exception e2) {
                    log.error("第3次调用paypal扣款失败，失败原因 {}", e2.getMessage() );
                }
            }
        }
        //当前只支持一个订单一个商品
        Capture capture = response.result().purchaseUnits().get(0).payments().captures().get(0);
        log.info("Capture id: {}", capture.id());
        log.info("status: {}", capture.status());
        log.info("invoice_id: {}", capture.invoiceId());
        //paypal交易号
        log.info("paypal交易号" + capture.id());
        //商户订单号,之前生成的带用户ID的订单号
        log.info(capture.invoiceId());
        paypalVo.setOId(capture.invoiceId());
        paypalVo.setCaptureId(capture.id());
        if("COMPLETED".equals(capture.status())) {
            paypalVo.setIsPaySuccess("SUCCESS");
        } else if("PENDING".equals(capture.status())) {
            log.info("status_details: {}", capture.captureStatusDetails().reason());
            String reason = "PENDING";
            if(capture.captureStatusDetails() != null && capture.captureStatusDetails().reason() != null) {
                reason = capture.captureStatusDetails().reason();
            }
            // 支付成功,状态为=PENDING
            log.info("支付成功,状态为=PENDING : {}", reason);
            paypalVo.setIsPaySuccess("PENDING");
        }else {
            paypalVo.setIsPaySuccess("FAILURE");
        }

        /*//一个订单多个商品
        List<PaypalVo> paypalVoList = new ArrayList<>();
        PaypalVo paypalVo = new PaypalVo();
        for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
            for (Capture capture : purchaseUnit.payments().captures()) {
                log.info("Capture id: {}", capture.id());
                log.info("status: {}", capture.status());
                log.info("invoice_id: {}", capture.invoiceId());
                //paypal交易号
                log.info("paypal交易号" + capture.id());
                //商户订单号,之前生成的带用户ID的订单号
                log.info(capture.invoiceId());
                paypalVo.setOId(capture.invoiceId());
                paypalVo.setCaptureId(capture.id());
                if("COMPLETED".equals(capture.status())) {
                    paypalVo.setIsPaySuccess("SUCCESS");
                } else if("PENDING".equals(capture.status())) {
                    log.info("status_details: {}", capture.captureStatusDetails().reason());
                    String reason = "PENDING";
                    if(capture.captureStatusDetails() != null && capture.captureStatusDetails().reason() != null) {
                        reason = capture.captureStatusDetails().reason();
                    }
                    // 支付成功,状态为=PENDING
                    log.info("支付成功,状态为=PENDING : {}", reason);
                    paypalVo.setIsPaySuccess("PENDING");
                }else {
                    paypalVo.setIsPaySuccess("FAILURE");
                }
            }
            paypalVoList.add(paypalVo);
        }*/

        return paypalVo;
    }

    /**
     * 支付后查询扣款信息
     */
    public String getCapture(String captureId) {
        String captureString = null;
        // 扣款查询
        CapturesGetRequest restRequest = new CapturesGetRequest(captureId);
        PayPalClient payPalClient = new PayPalClient();
        HttpResponse<com.paypal.payments.Capture> response;
        try {
            response = payPalClient.client().execute(restRequest);
            log.info("Status Code: " + response.statusCode());
            log.info("CaptureId: " + response.result().id());
            log.info("InvoiceId: " + response.result().invoiceId());
            log.info("Status: " + response.result().status());
            log.info("Links: ");
            for (LinkDescription link : response.result().links()) {
                log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
            }
            log.info("Full response body:");
            captureString = new JSONObject(new Json().serialize(response.result())).toString(4);
        } catch (IOException e) {
            log.info("查询支付扣款失败：{}",e.getMessage());
        }
        return captureString;
    }
}